<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>小球碰撞</title>
		<style type="text/css">
			body,html{
				height: 96%;
				padding: 6px;
			}
			#frame{
				border: 1px solid #ccc; /*外边框*/
				width: 100%;
				height: 100%;
				margin: 0 auto;	/*外框置中*/
				position: relative; /*相对定位,让小球能在中间绝对定位*/
			}
			#cicle{
				border-radius: 50%;
				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="frame"><div id="cicle"></div></div>
	</body>
	<script type="text/javascript">
		//获取元素
		var arcImgEle = document.getElementById("cicle");
		var frameEle = document.getElementById("frame");
		//------------------可变参数------------------
		//画布宽和高 （窗口大小）
		var width = frameEle.offsetWidth;
		var height = frameEle.offsetHeight;
		//侦数 每秒刷新次数
		var giant = 48;
		//速度 x方向和y方向的速度
		var vx = 3,vy = 5;
		//小球img起始位置，以小球图片左上角为标准
		var x = 100,y=100;
		//小球直径
		var radius = 60;
		//------------------修改元素css样式------------------
		//设置css样式
		arcImgEle.style.width = radius + "px";
		arcImgEle.style.height = radius + "px";
		randomCol();
		//------------------小球位置和颜色更新------------------
		//将小球图片放在div中xx，yy位置
		function drawArc(xx,yy){
			arcImgEle.style.left = xx + "px";
			arcImgEle.style.top = yy + "px";
		}
		//随机更换小球颜色
		function randomCol(){
			arcImgEle.style.backgroundColor = "#"+("00000"+((Math.random()*16777215+0.5)>>0).toString(16)).slice(-6); 
		}
		//以每秒giant帧 更新小球位置
		function updateArc(){
			x += vx;
			y += vy;
			width = frameEle.offsetWidth;
			height = frameEle.offsetHeight;
			//右边
			if (x+radius>=width) {
				x = width - radius;
				vx = -Math.abs(vx);
				randomCol();
			} 
			//下边
			if (y+radius>=height) {
				y = height - radius;
				vy = -Math.abs(vy);
				randomCol();
			}
			//左边
			if (x<=0) {
				x = 0;
				vx = Math.abs(vx);
				randomCol();
			} 
			//上边
			if (y<=0) {
				y = 0;
				vy = Math.abs(vy);
				randomCol();
			}
			drawArc(x,y);
		}
		window.onload = function(){
			setInterval("updateArc()",1000/giant);
		}
	</script>
</html>
